package org.framework.bean;

import org.framework.annotation.Action;
import org.framework.helper.ClassHelper;
import org.framework.utils.ArrayUtil;
import org.framework.utils.CollectionUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 * @Author xuelongjiang
 */
public class ControllerHelp {


    /**
     * 用于存放 请求与处理器映射关系
     */
    private static final Map<Request,Hanlder>  ACTION_MAP = new HashMap<Request, Hanlder>();


    static {

        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if(CollectionUtil.isNotEmpty(controllerClassSet)){
            //遍历获取 controller 类
            for(Class<?> controllerClass : controllerClassSet){
                //获取controller类的所有方法
                Method [] methods = controllerClass.getMethods();
                if(ArrayUtil.isNotEmpty(methods)){
                        for(Method method : methods){
                            //方法是否有action注解,有表示可以处理请求
                            if(method.isAnnotationPresent(Action.class)){
                                Action action = method.getAnnotation(Action.class);
                                String mapping = action.value();
                                //验证url映射规则
                                if(mapping.matches("\\w+:/\\w*")){
                                    String [] array = mapping.split(":");
                                    if(ArrayUtil.isNotEmpty(array)&& array.length == 2){
                                        String requestMethod  = array[0];
                                        String requestPath = array[1];
                                        Request request = new Request(requestPath,requestMethod);
                                        Hanlder hanlder = new Hanlder(controllerClass,method);
                                        //放入map
                                        ACTION_MAP.put(request,hanlder);
                                    }
                                }
                            }
                        }
                }
            }
        }
    }



    public  static Hanlder getHanlder(String requestMethod,String requestPath){
        Request request = new Request(requestPath,requestMethod);
        return  ACTION_MAP.get(request);
    }



}
